﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using GCC.APIContainer.Utilities;
using GCC.Container.Abstracts;
using GCC.Container.Models;

using Microsoft.AspNetCore.Mvc;

using Newtonsoft.Json.Linq;

using tcm.entity;
using tcm.Filters;
using tcm.request;
using tcm.response;
using tcm.utils;

namespace tcm.Controller
{
    [ApiController]
    [Route("tcm/phmList")]
    public class PhmListController : GCCAPIControllerBase
    {
        private readonly AbsGCCContext _context;

        public PhmListController(AbsGCCContext context) : base(context)
        {
            _context = context;
        }

        [HttpGet("query")]
        public DataResponse<List<PhmListExtInfo>> query([FromQuery] PhmListQueryReq req) 
        {
             var list = GCCEntrance.DBManager.GlobalDB.Select<PhmList>()
                .WhereIf(req.id != null, a => a.id == req.id)
                .WhereIf(!string.IsNullOrEmpty(req.list_name), a => a.list_name.Contains(req.list_name))
                .Where(a => a.status == 1)
                .OrderByDescending(a => a.create_date)
                .Count(out var count)
                .Page(req.PageIndex ?? 1, req.PageSize).ToList(a => new {
                    a,
                    createName = GCCEntrance.DBManager.GlobalDB.Select<SysUser>().Where(b => b.id == a.create_by).First(b => b.user_name)
                });

            List<PhmListExtInfo> phmLists = new List<PhmListExtInfo> ();
            for (int i = 0; i < list.Count; i++)
            {
                PhmListExtInfo phmList = new PhmListExtInfo();
                phmList.id = list[i].a.id;
                phmList.list_name = list[i].a.list_name;
                phmList.content = list[i].a.content;
                phmList.status = list[i].a.status;
                phmList.remark = list[i].a.remark;
                phmList.create_by = list[i].a.create_by;
                phmList.create_date = list[i].a.create_date;
                phmList.update_by = list[i].a.update_by;
                phmList.update_date = list[i].a.update_date;
                phmList.create_name = list[i].createName;

                phmLists.Add(phmList);
            }

            return HandleData(phmLists, count);
        }

        [HttpGet("queryAll")]
        public DataResponse<List<PhmList>> queryAll(string? list_name)
        {
            List<PhmList> list = GCCEntrance.DBManager.GlobalDB.Select<PhmList>()
                // like查询
                .WhereIf(!string.IsNullOrEmpty(list_name), a => a.list_name.Contains(list_name))
                .Where(a => a.status == 1).OrderByDescending(a => a.create_date).ToList();

            return HandleData(list);
        }

        [HttpGet("generic/query")]
        public DataResponse<List<PhmList>> queryDelivery()
        {
            List<PhmList> list = GCCEntrance.DBManager.GlobalDB.Select<PhmList>()
                 .WithSql("select t.*, count(l.phm_list_id) num " +
                 "           from tcm_phm_list t " +
                 "           left join tcm_phm_list_relation l on t.id = l.phm_list_id " +
                 "           where t.status = 1" +
                 "          GROUP BY t.id having num = 1").ToList();
            return HandleData(list);
        }

        [HttpGet("queryDetail")]
        public PhmListRes queryDetail(long id)
        {
            PhmListRes result = new PhmListRes();
            result.code = GlobalConstant.Success;
            List<PhmList> list = GCCEntrance.DBManager.GlobalDB.Select<PhmList>()
                .Where(a => a.id == id).ToList();
            if (list == null || list.Count == 0)
            {
                result.code = 1;
                result.msg = "PhmList为空!";
                return result;
            }

            result.phmList = list.First();

            var phmDbList = GCCEntrance.DBManager.GlobalDB.Select<PhmListRelation, Pharmaceutical>()
               .InnerJoin((a, b) => a.phm_id == b.id).Where((a, b) => a.phm_list_id == list.First().id).ToList((a, b) => new { a, b});
            List<PhmInfo> phmList = new List<PhmInfo>();
            if (phmList != null) 
            {
                for (int i = 0; i < phmDbList.Count; i++)
                {
                    PhmInfo info = BeanUtils.copy<PhmInfo, Pharmaceutical>(phmDbList[i].b);
                    info.phm_num = phmDbList[i].a.phm_num;
                    phmList.Add(info);
                }
            }
            
            result.pharmaceuticals = phmList;

            return result;
        }

        [HttpPost("add")]
        public Result add(request.PhmListReq req)
        {
            Result result = new Result();
            result.code = GlobalConstant.Success;

            List<PhmList> list = GCCEntrance.DBManager.GlobalDB.Select<PhmList>().Where(a => a.list_name == req.list_name).Where(a => a.status == 1).ToList();
            if (list != null && list.Count > 0)
            {
                result.code = GlobalConstant.Failure;
                result.msg = "药方已存在！";
                return result;
            }

            if (req.phm_id_list == null || req.phm_id_list.Count == 0) 
            {
                result.code = GlobalConstant.Failure;
                result.msg = "药方里无药品！";
                return result;
            }

            long id = IdUtils.getId();

            PhmList phmList = new PhmList();
            phmList.id = id;
            phmList.list_name = req.list_name;
            phmList.status = 1;
            phmList.content = req.content;
            phmList.remark = req.remark;
            phmList.create_date = DateTime.Now.ToLocalTime();
            phmList.update_date = DateTime.Now.ToLocalTime();

            var user = AuthManager.GetUserInfoByToken(_context, HttpContext.GetToken());
            if (user != null)
            {
                phmList.create_by = user.user_id;
                phmList.update_by = user.user_id;
            }

            int m = GCCEntrance.DBManager.GlobalDB.Insert(phmList).ExecuteAffrows();
            if (m <= 0)
            {
                result.code = GlobalConstant.Failure;
                result.msg = "入库失败！";
            }
            else
            {
                result.id = id;
                // 添加关系
                List<PhmListRelReq> phmIdList = req.phm_id_list;

                List<PhmListRelation> phmRelList = new List<PhmListRelation>();
                if (phmIdList != null) 
                {
                    for (int i = 0; i < phmIdList.Count; i++) 
                    {
                        PhmListRelReq relReq = phmIdList[i];
                        PhmListRelation phmListRelation = new PhmListRelation();
                        phmListRelation.phm_list_id = id;
                        phmListRelation.phm_id = relReq.phm_id;
                        phmListRelation.phm_num = relReq.phm_num;
                        phmListRelation.status = 1;
                        phmRelList.Add(phmListRelation);
                    }

                    int phmRList = GCCEntrance.DBManager.GlobalDB.Insert(phmRelList).ExecuteAffrows();
                    Console.WriteLine(phmRList);
                }
            }

            return result;
        }


        [HttpPut("update")]
        public Result update(request.PhmListReq req)
        {
            Result result = new Result();
            result.code = GlobalConstant.Success;

            if (req.id == null || req.id == 0)
            {
                result.code = 1;
                result.msg = "id为空！";
                return result;
            }
            
            List<PhmList> list = GCCEntrance.DBManager.GlobalDB.Select<PhmList>().Where(a => a.id == req.id).ToList();
            if (list == null || list.Count == 0) 
            {
                result.code = 1;
                result.msg = "id查询处方为空！";
                return result;
            }

            if (req.phm_id_list == null || req.phm_id_list.Count == 0)
            {
                result.code = GlobalConstant.Failure;
                result.msg = "药方里无药品！";
                return result;
            }

            PhmList phmList = list.First();
            phmList.list_name = req.list_name;
            phmList.content = req.content;
            phmList.remark = req.remark;
            var user = AuthManager.GetUserInfoByToken(_context, HttpContext.GetToken());
            if (user != null)
            {
                phmList.update_by = user.user_id;
            }
            phmList.update_date = DateTime.Now.ToLocalTime();

            int m = GCCEntrance.DBManager.GlobalDB.Update<PhmList>(phmList.id).SetSource(phmList).ExecuteAffrows();
            if (m <= 0)
            {
                result.code = 1;
                result.msg = "入库失败！";
            }
            else
            {
                result.id = phmList.id;
                // 添加关系
                List<PhmListRelReq> phmIdList = req.phm_id_list;
                if (phmIdList != null)
                {
                    // 新增处方药品
                    List<PhmListRelation> addList = new List<PhmListRelation>();

                    // 更新药品
                    List<PhmListRelation> updateList = new List<PhmListRelation>();

                    // 删除处方药品
                    List<PhmListRelation> delList = new List<PhmListRelation>();

                    // 查询处方现有的药品
                    List<PhmListRelation> phmListRelationList = GCCEntrance.DBManager.GlobalDB.Select<PhmListRelation>()
                        .Where(a => a.phm_list_id == req.id).Where(a => a.status == 1).ToList();


                    for (int i = 0; i < phmIdList.Count; i++)
                    {
                        long phmId = phmIdList[i].phm_id;
                        int phmNum = phmIdList[i].phm_num;
                        bool isExists = false;
                        for (int j = 0; j < phmListRelationList.Count; j++) 
                        {
                            long exitsPhmId = phmListRelationList[j].phm_id;
                            if (phmId == exitsPhmId) 
                            {
                                isExists = true;
                                PhmListRelation phmListRelation = phmListRelationList[j];
                                phmListRelation.phm_num = phmNum;
                                updateList.Add(phmListRelation);
                                break;
                            }
                        }

                        if (!isExists)
                        {
                            PhmListRelation phmListRelation = new PhmListRelation();
                            phmListRelation.phm_id = phmId;
                            phmListRelation.phm_num = phmNum;
                            phmListRelation.phm_list_id = phmList.id;
                            phmListRelation.status = 1;
                            addList.Add(phmListRelation);
                        }
                    }

                    int phmRList = GCCEntrance.DBManager.GlobalDB.Insert(addList).ExecuteAffrows();
                    Console.WriteLine(phmRList);

                    for (int i = 0; i < phmListRelationList.Count; i++)
                    {
                        long phmId = phmListRelationList[i].phm_id;
                        bool isDel = true;
                        for (int j = 0; j < phmIdList.Count; j++)
                        {
                            long exitsPhmId = phmIdList[j].phm_id;
                            if (phmId == exitsPhmId)
                            {
                                isDel = false;
                            }
                        }

                        if (isDel)
                        {
                            PhmListRelation phmListRelation = new PhmListRelation();
                            phmListRelation.phm_id = phmId;
                            phmListRelation.phm_list_id = phmList.id;
                            phmListRelation.status = 0;
                            delList.Add(phmListRelation);
                        }
                    }

                    // 删除多余
                    for (int i = 0; i < delList.Count; i++) 
                    {
                        int count = GCCEntrance.DBManager.GlobalDB.Update<PhmListRelation>()
                            .Set(a => a.status, 0)
                            .Where(a => a.phm_list_id == phmList.id)
                            .Where(a => a.phm_id == delList[i].phm_id).ExecuteAffrows();
                        Console.WriteLine(count);
                    }

                    // 更新
                    for (int i = 0; i < updateList.Count; i++)
                    {
                        int count = GCCEntrance.DBManager.GlobalDB.Update<PhmListRelation>()
                            .Set(a => a.phm_num, updateList[i].phm_num)
                            .Where(a => a.phm_list_id == phmList.id)
                            .Where(a => a.phm_id == updateList[i].phm_id).ExecuteAffrows();
                        Console.WriteLine(count);
                    }

                }
            }

            return result;
        }

        [HttpDelete("delete/{phm_list_id}")]
        public Result delete([FromRoute] long phm_list_id)
        {
            Result result = new Result();
            result.code = GlobalConstant.Success;
            result.msg = "删除成功！";
            if (phm_list_id == null || phm_list_id == 0) 
            {
                result.code = GlobalConstant.Failure;
                result.msg = "phm_list_id为空！";
                return result;
            }

            _=GCCEntrance.DBManager.GlobalDB.Update<PhmListRelation>()
                            .Set(a => a.status, 0)
                            .Where(a => a.phm_list_id == phm_list_id).ExecuteAffrows();

            _ = GCCEntrance.DBManager.GlobalDB.Update<PhmList>()
                            .Set(a => a.status, 0)
                            .Where(a => a.id == phm_list_id).ExecuteAffrows();

            return result;
        }
    }
}
